



import java.util.Enumeration;
import java.util.Hashtable;

import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;

import tool.FileUtils;
import tool.Mp3Handler;

import boot.Boot;



public class Mp3Browser {

	private Boot midlet;
	private Mp3Handler handler;
	private Hashtable fileLists;
	private String[] filter;
	private long collectionVolume;

	public Mp3Browser(Boot aMidlet) throws Throwable {
		super();
		collectionVolume = 0;
		midlet = aMidlet;
		fileLists = new Hashtable();
		
		setupLists();
	}
	

	public Mp3Browser(Boot aMidlet, String[] aFilter) throws Throwable {
		super();
		midlet = aMidlet;
		fileLists = new Hashtable();
		filter = aFilter;
		
		setupLists();
	}
	
	private void setupLists() throws Throwable {
		String[] dirNames = midlet.getDirNames();
		
		for (int i = 0; i < dirNames.length; i++) {
			String dir = dirNames[i];
			
			if (!isFiltered(dir)) {
				FileConnection connection
					= (FileConnection) Connector.open(dir);
				Enumeration files = connection.list("*.mp3", true);
				collectionVolume += connection.directorySize(false);
				connection.close();
				fileLists.put(dir, files);
			}
		}
	}

	private boolean isFiltered(String dir) {
		boolean isFiltered = false;
		for (int i = 0; (filter != null) && (i < filter.length) && (!isFiltered); i++) {
			isFiltered = dir.equals(FileUtils.SD_CARD + "/" + filter[i]);
		}
		return isFiltered;
	}


	public void browse(Mp3Handler aHandler) throws Throwable {
		handler = aHandler;
		
		Enumeration keys = fileLists.keys();
		
		while (keys.hasMoreElements()) {
			String key = (String) keys.nextElement();
			Enumeration files = (Enumeration) fileLists.get(key);
			
			while (files.hasMoreElements()) {
				String mp3 = (String) files.nextElement();
				handler.handleNextMP3(key, mp3);
			}
		}
	}
	
	
	public long getCollectionVolume() {
		return collectionVolume;
	}
}
